﻿using System;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlServerCe;
using Microsoft.WindowsMobile.PocketOutlook;

namespace smsorder
{
    
    public partial class mainform : Form
    {

        class myorder
        {
            public string name;
            public double tot;
            public int cnt;
        }
        private List<myorder> mybuy;
        public mainform()
        {
            mybuy = new List<myorder>();
            InitializeComponent();
        }
        private static string dbpath = @"My Documents\smsorder.sdf";
        private static string dbconn = "Data Source=" + dbpath;
        private static string cooktxt = @"My Documents\cook.txt";
        private static string drinktxt = @"My Documents\drink.txt";
        private static string dbbk = @"My Documents\order_bak";
        private void sqlnon(string sql)
        {
            SqlCeConnection conn = new SqlCeConnection();
            conn.ConnectionString = dbconn;
            conn.Open();
            SqlCeCommand cmd = new SqlCeCommand();
            cmd.Connection = conn;
            cmd.CommandText = sql;
            cmd.ExecuteNonQuery();
            conn.Close();
        }
       
        private void butresetdata_Click(object sender, EventArgs e)
        {
            
            bool delok = true;
            
            if (File.Exists(dbpath))
            {
                try
                {
                    File.Delete(dbpath);
                }
                catch(IOException err )
                {
                    MessageBox.Show("无法删除数据库文件\n请确认没有其他程序使用它", "错误", MessageBoxButtons.OK, MessageBoxIcon.Asterisk,MessageBoxDefaultButton.Button1);
                    delok = false;
                }
            }
            if (delok)
            {
                sysinfo.Text = "重生时间比较长，请耐心等待";
                SqlCeEngine eng = new SqlCeEngine();
                eng.LocalConnectionString = dbconn;
                eng.CreateDatabase();

                SqlCeConnection conn = new SqlCeConnection();
                conn.ConnectionString = dbconn;
                conn.Open();
                SqlCeCommand cmd = new SqlCeCommand();
                cmd.Connection = conn;
                cmd.CommandText=" CREATE TABLE cook "+
                                " ( cid integer PRIMARY KEY ,"+
                                "  cname nchar(20) ,"+
                                "  cprice money ,"+
                                "  cinfo nchar(200) ,"+
                                "  cnt integer )";
                cmd.ExecuteNonQuery();
                cmd.CommandText=" CREATE TABLE drink "+
                                " ( did integer PRIMARY KEY ,"+
                                "  dname nchar(20) ,"+
                                "  dprice money ,"+
                                "  dinfo nchar(200),"+
                                "   cnt integer )";
                cmd.ExecuteNonQuery();
                conn.Close();
                sysinfo.Text = "数据库重生成功";
             
            }
        }

        private void butrestore_Click(object sender, EventArgs e)
        {
            if (File.Exists(dbbk))
            {
                File.Copy(dbbk, dbpath, true);
            }
            else
            {
                MessageBox.Show("还没有进行备份");
            }
            sysinfo.Text="导入备份成功";
        }

        private void butloadfile_Click(object sender, EventArgs e)
        {
            bool ce = false;
            bool de = false;
            if (File.Exists(cooktxt))
            {
                ce = true;
            }
            if (File.Exists(drinktxt))
            {
                de = true;
            }
            //manage cook 
            FileStream fs = new FileStream(cooktxt, FileMode.OpenOrCreate);
            if (ce)
            {
                //cooktxt exist
                StreamReader rd = new StreamReader(fs, Encoding.UTF8);
                string line;
                int ind=0;
                bool workok = false;
                while ((line = rd.ReadLine()) != null )
                {
                    if (line.StartsWith("--"))
                    {
                        workok = true;
                        continue;
                    }
                    if (workok)
                    {
                        string[] strarr = line.Split(new char[] {','});
                        if (strarr.Length <= 1)
                        {
                            continue;
                        }
                        string name = strarr[0].Trim();
                        string price = strarr[1].Trim();
                        string info = "";
                        for (int i = 2; i < strarr.Length; i++)
                        {
                            info += strarr[i].Trim();
                        }
                        ind++;
                        string sql = string.Format("insert into cook values({0},'{1}','{2}','{3}',0)", ind, name, price, info);
                        //MessageBox.Show(sql);
                        sqlnon(sql);
                    }
                }
            }
            else
            {
                StreamWriter tw = new StreamWriter(fs,Encoding.UTF8);
                tw.WriteLine("这是炒菜数据");
                tw.WriteLine("请按  名称 , 价格 , 介绍  的格式每行一种炒菜\n介绍可以不写，每项必须要有','(英文逗号)分隔，比如:");
                tw.WriteLine("鱼香肉丝 , 8.55  ");
                tw.WriteLine("木须肉 , 5.82  , 就是蘑菇木耳炒肉");
                tw.WriteLine("-----在横线下写出炒菜数据-----");
                tw.Close();
            }
            fs.Close();
            fs=new FileStream(drinktxt, FileMode.OpenOrCreate);
            if (de)
            {//drink exist
                //cooktxt exist
                StreamReader rd = new StreamReader(fs, Encoding.UTF8);
                string line;
                int ind = 0;
                bool workok = false;
                while ((line = rd.ReadLine()) != null)
                {
                    if (line.StartsWith("--"))
                    {
                        workok = true;
                        continue;
                    }
                    if (workok)
                    {
                        string[] strarr = line.Split(new char[] { ',' });
                        if (strarr.Length <= 1)
                        {
                            continue;
                        }
                        string name = strarr[0].Trim();
                        string price = strarr[1].Trim();
                        string info = "";
                        for (int i = 2; i < strarr.Length; i++)
                        {
                            info += strarr[i].Trim();
                        }
                        ind++;
                        string sql = string.Format("insert into drink values({0},'{1}','{2}','{3}',0)", ind, name, price, info);
                        //MessageBox.Show(sql);
                        sqlnon(sql);
                    }
                }
            }
            else
            {
                StreamWriter tw = new StreamWriter(fs, Encoding.UTF8);
                tw.WriteLine("这是饮料数据");
                tw.WriteLine("请按  名称 , 价格 , 介绍  的格式每行一种饮料\n介绍可以不写，每项必须要有','(英文逗号)分隔，比如:");
                tw.WriteLine("咖啡 , 8.5  ");
                tw.WriteLine("可乐 , 2.8 , 挺难喝的");
                tw.WriteLine("-----在横线下写出饮料数据-----");
                tw.Close();
            }
            fs.Close();
            sysinfo.Text = "导入成功";
        }

        private void butbackup_Click(object sender, EventArgs e)
        {
            if (File.Exists(dbpath))
            {
                File.Copy(dbpath,dbbk,true);
            }
            else
            {
                MessageBox.Show("没有找到数据库，请重生数据库");
            }
            sysinfo.Text = "备份成功";
        }

        private void cooking_Click(object sender, EventArgs e)
        {
            
            
        }

        private void cooking_GotFocus(object sender, EventArgs e)
        {
           
        }

        private void fillcook()
        {
            SqlCeConnection conn = new SqlCeConnection();
            conn.ConnectionString = dbconn;
            conn.Open();
            SqlCeCommand cmd = new SqlCeCommand();
            cmd.Connection = conn;
            String sql = "select cname,cprice from cook order by cnt desc";
            cmd.CommandText = sql;
            SqlCeDataReader rd = cmd.ExecuteReader();
            cooklist.Items.Clear();
            while (rd.Read())
            {
                string name = rd["cname"].ToString().Trim();
                string price = rd["cprice"].ToString().Trim();
                cooklist.Items.Add(name+" ￥"+price);
                 
            }
            conn.Close();
        }
        private void filldrink()
        {
            SqlCeConnection conn = new SqlCeConnection();
            conn.ConnectionString = dbconn;
            conn.Open();
            SqlCeCommand cmd = new SqlCeCommand();
            cmd.Connection = conn;
            string  sql = "select dname , dprice from drink order by cnt desc";
            cmd.CommandText = sql;
            SqlCeDataReader rd = cmd.ExecuteReader();
            drinklist.Items.Clear();
            while (rd.Read())
            {
                string name = rd["dname"].ToString().Trim();
                string price = rd["dprice"].ToString().Trim();
                drinklist.Items.Add(name + " ￥" + price);
            }
            conn.Close();
        }
        private void maintab_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (maintab.SelectedIndex)
            {
                case 0:
                    //MessageBox.Show("cooking");
                    fillcook();
                    break;
                case 1:
                    //MessageBox.Show("drinking");
                    filldrink();
                    break;
                case 2:
                    fillsms();
                    break;

            }
        }

        private void bestcook_SelectedIndexChanged(object sender, EventArgs e)
        {
            
        }

        private void mainform_Load(object sender, EventArgs e)
        {
            //fillcook();
            //filldrink();
            cooknum.Text = trackcooknum.Value.ToString();
            drinknum.Text = trackdrinknum.Value.ToString();
            
        }

        private void maintab_Validated(object sender, EventArgs e)
        {
            
        }

        private void bestdrink_SelectedIndexChanged(object sender, EventArgs e)
        {
            
        }
      
        private void buycook(object sender ,int type)//list is 1 and combox is 0
        {
            string name;
            if (type == 1)
            {
                name = (string)((ListBox)sender).SelectedItem;
            }else
            {
                name = (string)((ComboBox)sender).SelectedItem;
            }
            name = name.Trim();
            MessageBox.Show(name);

            SqlCeConnection conn = new SqlCeConnection();
            conn.ConnectionString = dbconn;
            conn.Open();
            SqlCeCommand cmd = new SqlCeCommand();
            cmd.Connection = conn;
            string sql = string.Format("select * from cook where cname ='{0}' ",name);
            MessageBox.Show(sql);
            cmd.CommandText = sql;
            SqlCeDataReader rd=cmd.ExecuteReader();
            rd.Read();
            string showout = "名称："+rd.GetValue(1) +"\n"+"单价:" + rd.GetValue(2)+"\n"+"介绍："+rd.GetValue(3);
            MessageBox.Show(showout);
            conn.Close();
            /*
             * 问题 想开一个对话框 ， 传入字符串数据 ，用 mainform 的public 属性传参
             * 其实 通过构造函数就行。
             */

           
        }
        private void cooklist_SelectedIndexChanged(object sender, EventArgs e)
        {
            bestcook.Text = cooklist.SelectedItem.ToString();
        }

        private void mynum_ValueChanged(object sender, EventArgs e)
        {
            cooknum.Text = trackcooknum.Value.ToString();

        }

        private void trackdrinknum_ValueChanged(object sender, EventArgs e)
        {
            drinknum.Text = trackdrinknum.Value.ToString();
        }

        private void butbuycook_Click(object sender, EventArgs e)
        {
            string name = bestcook.Text.Split(new char[]{ ' '})[0].Trim();
            
            SqlCeConnection conn = new SqlCeConnection();
            conn.ConnectionString = dbconn;
            conn.Open();
            SqlCeCommand cmd = new SqlCeCommand();
            cmd.Connection = conn;
            int cid=0;
            cmd.CommandText = string.Format("select cid ,cprice from cook where cname='{0}' ",name);
            SqlCeDataReader rd = cmd.ExecuteReader();
            rd.Read();
            cid=rd.GetInt32(0);
            myorder tmp = new myorder();
            tmp.name = name;
            int cnt= int.Parse(cooknum.Text);
            tmp.cnt = cnt;
            tmp.tot = cnt * (double)rd.GetDecimal(1);
            mybuy.Add(tmp);
            cmd.CommandText = "update cook set cnt = cnt+" + cnt+" where cid="+cid;
            cmd.ExecuteNonQuery();
            conn.Close();
            //MessageBox.Show(name);
            trackcooknum.Value = 1;

        }

        private void drinklist_SelectedIndexChanged(object sender, EventArgs e)
        {

            bestdrink.Text = drinklist.SelectedItem.ToString();
        }

        private void fillsms(){
            string txt="";
            double sum = 0;
            if (mybuy.Count > 0)
            {
                foreach (myorder or in mybuy)
                {
                    txt = txt + string.Format("{0} 数量:{1}", or.name, or.cnt) + "\r\n";
                    sum += or.tot;
                }
                txt += string.Format("总价:{0}", sum)+"\r\n";
                txt += txtname.Text;
               // MessageBox.Show(txt);
                smstxt.Text = txt;
            }
            else
            {
                smstxt.Text = "没有购物信息";
            }
        }
        private void butclearbuy_Click(object sender, EventArgs e)
        {
            mybuy.Clear();
            fillsms();
        }

        private void smstxt_TextChanged(object sender, EventArgs e)
        {

        }

        private void butbuydrink_Click(object sender, EventArgs e)
        {
            string name = bestdrink.Text.Split(new char[] { ' ' })[0].Trim();
            SqlCeConnection conn = new SqlCeConnection();
            conn.ConnectionString = dbconn;
            conn.Open();
            SqlCeCommand cmd = new SqlCeCommand();
            cmd.Connection = conn;
            int did = 0;
            cmd.CommandText = string.Format("select did ,dprice from drink where dname='{0}' ", name);
            SqlCeDataReader rd = cmd.ExecuteReader();
            rd.Read();
            did = rd.GetInt32(0);
            myorder tmp = new myorder();
            tmp.name = name;
            int cnt = int.Parse(drinknum.Text);
            tmp.cnt = cnt;
            tmp.tot = cnt * (double)rd.GetDecimal(1);
            mybuy.Add(tmp);
            cmd.CommandText = "update drink set cnt = cnt +" + cnt + " where did = " + did;
            cmd.ExecuteNonQuery();
            conn.Close();
            trackdrinknum.Value = 1;
        }

        private void button1_Click(object sender, EventArgs e)
        {
           // MessageBox.Show(smstxt.Text);
            sysinfo.Text = "菜单已发送";
            SmsMessage sms = new SmsMessage();
            sms.Body = smstxt.Text;
            sms.To.Add(new Recipient(txtnum.Text));
            sms.RequestDeliveryReport = false;
            sms.Send();
        }

    }
}